package dbops

import (
	"time"
	"gitee.com/DengAnbang/goutils/dbutils"
	"gitee.com/DengAnbang/Computation/src/bean"
	"math/rand"
	"fmt"
)

func UserRegister(loginName, pwd, name string) (user bean.UserBean, err error) {
	if len(loginName) == 0 {
		return user, bean.NewErrorMessage("账号不能为空")
		//return user, httpUtils.NewResultError(code.NormalErr, "账号不能为空")
	}
	if len(pwd) == 0 {
		return user, bean.NewErrorMessage("密码不能为空")
	}
	user, err = SelectUser(loginName)
	if len(user.UserId) > 0 {
		return user, bean.NewErrorMessage("用户已经存在了!")
	}
	if len(name) <= 0 {
		name = fmt.Sprintf("用户%v", rand.Int31n(9999))
	}
	created := time.Now().Format("2006-01-02 15:03:04")
	stmtIn, err := dbConn.Prepare("INSERT INTO table_user (login_name,pwd,name,created)VALUES(?,?,?,?)")
	if err != nil {
		return
	}
	_, err = stmtIn.Exec(loginName, pwd, name, created)
	defer stmtIn.Close()
	user, _ = SelectUser(loginName)
	return
}

func UserLogin(loginName, pwd string) (user bean.UserBean, err error) {
	if len(loginName) == 0 {
		return user, bean.NewErrorMessage("登陆名字不能为空")
	}
	if len(pwd) == 0 {
		return user, bean.NewErrorMessage("密码不能为空")
	}
	user, err = SelectUser(loginName)
	if len(user.UserId) <= 0 {
		return user, bean.NewErrorMessage("用户不存在或密码错误!")
	}
	if user.Pwd != pwd {
		return user, bean.NewErrorMessage("用户不存在或密码错误!")
	}
	return
}

func DeleteUser(loginName string) error {
	stmtDel, err := dbConn.Prepare("DELETE FROM table_user WHERE login_name=?")
	if err != nil {
		return err
	}
	_, err = stmtDel.Exec(loginName)
	stmtDel.Close()
	return err
}
func SelectUser(loginName string) (bean.UserBean, error) {
	var user bean.UserBean
	stmtOut, err := dbConn.Prepare("SELECT * FROM table_user WHERE login_name = ?")
	if err != nil {
		return user, err
	}
	defer stmtOut.Close()
	rows, err := stmtOut.Query(loginName)
	if err != nil {
		return user, err
	}
	defer rows.Close()
	if rows.Next() {
		var strings map[string]string
		strings, err = dbutils.GetRowsMap(rows)
		if err != nil {
			return user, err
		}
		user = bean.UserBean{
			UserName:  strings["name"],
			UserId:    strings["user_id"],
			LoginName: strings["login_name"],
			Pwd:       strings["pwd"],
		}
	}
	return user, err
}
